package com.zijunlin.Zxing.Demo;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

public class ImageActivity extends Activity {
	private static final String TAG = "ImageActivity";
	// 显示二维码图片
	private ImageView qr_image;

	private ImageView moreButton;
	private Button cancelButton;
	private int imageW,imageH;

	private final static int QR_WIDTH = 425, QR_HEIGHT = 425;
	private PopupWindow mPopupWindow;
	// 图片宽度的一般
	private static final int IMAGE_HALFWIDTH = 30;
	// 插入到二维码里面的图片对象
	private Bitmap mBitmap;
	// 需要插图图片的大小 这里设定为40*40
	int[] pixels = new int[2*IMAGE_HALFWIDTH * 2*IMAGE_HALFWIDTH];
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.twodimensionalcode_myqr);
		init();
	}

	private void init() {
		qr_image = (ImageView) findViewById(R.id.qr_image);
		moreButton = (ImageView) findViewById(R.id.my_more_button);
		cancelButton = (Button) findViewById(R.id.cancel_button);
		// 构造需要插入的图片对象
		mBitmap = ((BitmapDrawable) getResources().getDrawable(
				R.drawable.logo)).getBitmap();
		// 缩放图片
		Matrix m = new Matrix();
		float sx = (float) 2*IMAGE_HALFWIDTH / mBitmap.getWidth();
		float sy = (float) 2*IMAGE_HALFWIDTH / mBitmap.getHeight();
		m.setScale(sx, sy);
		// 重新构造一个40*40的图片
		mBitmap = Bitmap.createBitmap(mBitmap, 0, 0, mBitmap.getWidth(),
				mBitmap.getHeight(), m, false);

		//		createImage();
		try {
//			String encoderContent = "BEGIN:VCARD"+"\nVERSION:3.0" + "\nN:宋旋" + "\nORG:上海富可"+"\nTEL;CELL:15012312341"+"\nURL:http://www.diaoyanbang.net/"+"\nEMAIL:sx@51im.cn"+"\nEND:VCARD";     
			String encoderContent = "http://www.diaoyanbang.net/"; 
			cretaeBitmap(new String(encoderContent.getBytes(),
					"ISO-8859-1"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (WriterException e) {
			e.printStackTrace();
		}
		moreButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				popupWindow();
			}
		});
		
		cancelButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

	/*// 生成QR图    纯文本
	private void createImage() {
		try {
			QRCodeWriter writer = new QRCodeWriter();

			String text = "张三\n富可技术\n研发软件\n12345678906@163.com\n";

			Log.i(TAG, "生成的文本：" + text);
			if (text == null || "".equals(text) || text.length() < 1) {
				return;
			}

			BitMatrix martix = writer.encode(text, BarcodeFormat.QR_CODE,
					QR_WIDTH, QR_HEIGHT);

			System.out.println("w:" + martix.getWidth() + "h:"
					+ martix.getHeight());

			Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
			hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
			BitMatrix bitMatrix = new QRCodeWriter().encode(text,
					BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT, hints);
			int[] pixels = new int[QR_WIDTH * QR_HEIGHT];
			for (int y = 0; y < QR_HEIGHT; y++) {
				for (int x = 0; x < QR_WIDTH; x++) {
					if (bitMatrix.get(x, y)) {
						pixels[y * QR_WIDTH + x] = 0xff000000;
					} else {
						pixels[y * QR_WIDTH + x] = 0xffffffff;
					}

				}
			}

			Bitmap bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT,
					Bitmap.Config.ARGB_8888);

			bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT);
			qr_image.setImageBitmap(bitmap);

		} catch (WriterException e) {
			e.printStackTrace();
		}
	}*/
	/**
	 * 生成二维码
	 * 
	 * @param 字符串
	 * @return Bitmap
	 * @throws WriterException
	 */
	public Bitmap cretaeBitmap(String str) throws WriterException {
//		Result result = new Result(text, rawBytes, resultPoints, format);
//		AddressBookParsedResult addressResult = new AddressBookParsedResult
//				(names, pronunciation, phoneNumbers, phoneTypes, emails, emailTypes, instantMessenger, note, addresses, addressTypes, org, birthday, title, url) ;
		// 生成二维矩阵,编码时指定大小,不要生成了图片以后再进行缩放,这样会模糊导致识别失败
		BitMatrix matrix = new MultiFormatWriter().encode(str,
				BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT);
		int width = matrix.getWidth();
		int height = matrix.getHeight();
		// 二维矩阵转为一维像素数组,也就是一直横着排了
		int halfW = width / 2;
		int halfH = height / 2;
		int[] pixels = new int[width * height];
		for (int y = 0; y < height; y++) {
			for (int x = 0; x < width; x++) {
				if (x > halfW - IMAGE_HALFWIDTH && x < halfW + IMAGE_HALFWIDTH && y > halfH - IMAGE_HALFWIDTH
						&& y < halfH + IMAGE_HALFWIDTH) {
					pixels[y * width + x] = mBitmap.getPixel(x - halfW + IMAGE_HALFWIDTH, y
							- halfH + IMAGE_HALFWIDTH);
				} else {
					if (matrix.get(x, y)) {
						pixels[y * width + x] = 0xff000000;
					}
				}

			}
		}
		Bitmap bitmap = Bitmap.createBitmap(width, height,
				Bitmap.Config.ARGB_8888);
		// 通过像素数组生成bitmap
		bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
		InputStream is = getResources().openRawResource(
				R.drawable.white);
		Bitmap mBitmap = BitmapFactory.decodeStream(is);
		qr_image.setImageBitmap(compositeImages(mBitmap,bitmap));
		return bitmap;
	}
	
	/** 
     * 图像的合成，可以通过在同一个Canvas中绘制两张图片。 
     * 只是在绘制第二章图片的时候，需要给Paint指定一个变幻模式TransferMode。 
     * 在Android中有一个XFermode所有的变幻模式都是这个类的子类 
     * 我们需要用到它的一个子类PorterDuffXfermode,关于这个类，其中用到PorterDuff类 
     * 这个类很简单，就包含一个Enum是Mode，其中定义了一组规则，这组规则就是如何将 
     * 一张图像和另一种图像进行合成 
     * 关于图像合成有四种模式，LIGHTEN,DRAKEN,MULTIPLY,SCREEN 
     */  
    private Bitmap compositeImages(Bitmap srcBitmap,Bitmap dstBitmap){  
          
        Bitmap bmp = null;  
        //下面这个Bitmap中创建的函数就可以创建一个空的Bitmap   
        bmp = Bitmap.createBitmap(srcBitmap.getWidth(), srcBitmap.getHeight(), srcBitmap.getConfig());  
        Paint paint = new Paint();  
        Canvas canvas = new Canvas(bmp);  
        //首先绘制第一张图片，很简单，就是和方法中getDstImage一样   
        canvas.drawBitmap(srcBitmap, 50, 100, paint);        
          
        //在绘制第二张图片的时候，我们需要指定一个Xfermode   
        //这里采用Multiply模式，这个模式是将两张图片的对应的点的像素相乘   
        //，再除以255，然后以新的像素来重新绘制显示合成后的图像   
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DARKEN));  
        canvas.drawBitmap(dstBitmap, 0, 0, paint);  
          
        return bmp;  
    }  

    
	/**
	 * 更多选项窗口
	 * 
	 * @param context
	 * @return
	 */
	public void popupWindow() {
		View layoutView = View.inflate(ImageActivity.this, R.layout.twodimensionalcode_more,
				null);
		
		TextView my_share = (TextView) layoutView.findViewById(R.id.my_share);
		TextView my_qrcode = (TextView) layoutView.findViewById(R.id.my_qrcode);
		TextView my_cancel = (TextView) layoutView.findViewById(R.id.my_cancel);

		my_cancel.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				mPopupWindow.dismiss();
			}
		});
		my_share.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				mPopupWindow.dismiss();
				Toast.makeText(ImageActivity.this, "分享", Toast.LENGTH_LONG)
				.show();
			}
		});
		my_qrcode.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				mPopupWindow.dismiss();
				try {
					Bitmap bitmap = ((BitmapDrawable) qr_image.getDrawable()).getBitmap();
					if (bitmap != null) {
						saveBitmap(bitmap);
					}else {
						Toast.makeText(ImageActivity.this, "保存失败，请重新保存", Toast.LENGTH_LONG)
						.show();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
		mPopupWindow = new PopupWindow(layoutView, LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT, true);
		// 点击外窗口自动消失
		mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
		mPopupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
		mPopupWindow.setOutsideTouchable(true);
		mPopupWindow.update();
		mPopupWindow.setTouchable(true);
		mPopupWindow.setFocusable(true);
		// mPopupWindow.setAnimationStyle(R.style.MyDialogStyleBottom);
		// 设置layout在PopupWindow中显示的位置
		mPopupWindow.showAtLocation(layoutView, Gravity.BOTTOM
				| Gravity.CENTER_HORIZONTAL, 0, 0);

		layoutView = null;
		my_share = null;
		my_qrcode = null;
		my_cancel = null;
	}
	public void saveBitmap(Bitmap bitmap) throws IOException {
		//SD卡是否可用
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
		
			//检查是或有保存图片的文件夹，没有就创建一个
			String fileUrl = Environment.getExternalStorageDirectory()+"/DCIM/Camera/";
			File file = new File(fileUrl);
			if (!file.exists()) {
				System.out.println("无此文件夹");
				file.mkdir();
			}
			File f = new File(fileUrl+"haoxunqr"+getCharacterAndNumber()+".jpg/");
			System.out.println(fileUrl.toString());
			FileOutputStream out;
		try {
			out = new FileOutputStream(f);
			if (bitmap.compress(Bitmap.CompressFormat.PNG, 70, out)) {
				out.flush();
				out.close();
			}
			Toast.makeText(ImageActivity.this, "图片已保存到/sdcard/DCIM/Camera/", Toast.LENGTH_LONG)
			.show();
		} catch (FileNotFoundException e) {
			Toast.makeText(ImageActivity.this, "保存失败，请重新保存", Toast.LENGTH_LONG)
			.show();
		} catch (IOException e) {
			Toast.makeText(ImageActivity.this, "保存失败，请重新保存", Toast.LENGTH_LONG)
			.show();
		}
		}else {
			Toast.makeText(ImageActivity.this, "SD卡不可用或不存在", Toast.LENGTH_LONG)
			.show();
		}
	}
	public static String getCharacterAndNumber() { 
		String rel=""; 
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss"); 
		Date curDate = new Date(System.currentTimeMillis()); 
		rel = formatter.format(curDate); 
		return rel; 
		}
}
